<!-- PaginationComponent.vue -->
<template>
  <div class="pagination-container">
    <el-pagination
      :total="totalItems"
      :page-size="itemsPerPage"
      :current-page="currentPage"
      @current-change="handlePageChange"
      @size-change="handlePageSizeChange"
      layout="total, prev, pager, next, sizes"
      :page-sizes="[10, 20, 30, 50]"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import Task from '../apis/Task';

const props = defineProps({
  totalItems: {
    type: Number,
    required: true,
  },
  itemsPerPage: {
    type: Number,
    required: true,
  },
  currentPage: {
    type: Number,
    required: true,
  },
});

const emit = defineEmits(['dataChange']);

const fetchData = async (page, size) => {
  try {
    const response = await Task.getTaskSelect({
      currentPage: page,
      pageSize: size,
    });
    if (response.data == null) {
      throw new Error('没有符合要求的数据，请重新尝试');
    }
    emit('dataChange', {
      tableData: response.data,
      totalItems: response.total,
    });
  } catch (error) {
    ElNotification({
      title: '错误',
      message: error.message,
      type: 'error',
    });
  }
};

const handlePageChange = (page) => {
  emit('currentChange', page); // 触发父组件页数改变
  fetchData(page, props.itemsPerPage); // 数据请求
};

const handlePageSizeChange = (size) => {
  emit('sizeChange', size); // 触发父组件每页条目数改变
  fetchData(props.currentPage, size); // 数据请求
};

// 使用watch监听分页参数变化，并更新数据
watch(
  () => props.currentPage,
  (newPage) => {
    fetchData(newPage, props.itemsPerPage);
  },
);

watch(
  () => props.itemsPerPage,
  (newSize) => {
    fetchData(props.currentPage, newSize);
  },
);
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-pagination {
  font-size: 14px;
  padding: 0;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.el-pagination .el-pagination__sizes select {
  margin-right: 10px;
  padding: 2px 10px;
}

.el-pagination .el-button {
  font-size: 12px;
}
</style>
